<template>
  <div class="content">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <!-- 搜索框 -->
    <div class="search-box">
      <input 
        type="text" 
        v-model="searchKeyword" 
        placeholder="搜索名字或类型" 
        class="search-input"
      >
      <span v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</span>
    </div>

    <!-- 新增tab切换 -->
    <div class="tab-switch">
      <span :class="['tab-btn', {active: tabType === 3}]" @click="switchTab(3)">免广小游</span>
      <span :class="['tab-btn', {active: tabType === 1}]" @click="switchTab(1)">GM游戏</span>
      <span :class="['tab-btn', {active: tabType === 2}]" @click="switchTab(2)">买断GM</span>
    </div>

    <div class="game-list" @touchstart="handleTouchStart">
      <div v-if="isLoading" class="loading">
        加载中...
      </div>
      <div v-else-if="filteredGames.length === 0" class="no-result">
        暂无结果
      </div>
      <div class="game-item" v-for="game in filteredGames" :key="game.id" @click="toDetail(game.id)">
        <!-- 左侧游戏图标 -->
        <img :src="game.icon" alt="游戏图标" class="game-icon">

        <!-- 游戏信息部分 -->
        <div class="game-info">
          <div class="game-name-div">
            <!-- 游戏名称 -->
            <span class="game-name">{{ game.name }}</span>
            <span v-if="game.cate == 20" class="tag unified-rare-tag">稀有</span>
            <span v-if="game.cate == 90" class="tag unified-buyout-tag">买断</span>
            <span class="tag">安卓{{game.apple ? '+苹果' : ''}}</span>
          </div>
          <!-- 游戏标签 -->
          <div class="game-tags">
            <span v-for="tag in tagsArray(game.tags)" :key="tag" class="tag">{{ tag }}</span>
          </div>
          <!-- 游戏描述 -->
          <span class="game-desc">{{ game.intro }}</span>
        </div>

        <!-- 下载按钮 -->
        <a 
          v-if="!isAppleDevice && game.downloadUrl" 
          :href="game.downloadUrl" 
          class="download-btn" 
          target="_blank"
          @click.stop
        >下载</a>
        <span 
          v-else 
          class="download-btn" 
        >下载</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomePage'
}
</script>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const games = ref([])
const searchKeyword = ref('')
const tabType = ref(parseInt(route.query.tab || localStorage.getItem('homeTabType') || '1'))
const isLoading = ref(false)
const hasLoaded = ref(false)

// 检测是否为苹果设备
const isAppleDevice = computed(() => {
  const userAgent = navigator.userAgent.toLowerCase()
  return /iphone|ipad|ipod|macintosh/.test(userAgent)
})

const filteredGames = computed(() => {
  let filtered = games.value
  if (tabType.value === 3) {
    filtered = filtered.filter(game => game.cate == 5)
  } else if (tabType.value === 1) {
    filtered = filtered.filter(game => game.cate > 5 && game.cate < 90)
  } else if (tabType.value === 2) {
    filtered = filtered.filter(game => game.cate == 90)
  }
  if (!searchKeyword.value) {
    return filtered
  }
  const keyword = searchKeyword.value.toLowerCase()
  return filtered.filter(game => 
    game.name.toLowerCase().includes(keyword) ||
    game.tags.toLowerCase().includes(keyword) ||
    game.intro.toLowerCase().includes(keyword)
  )
})

const clearSearch = () => {
  searchKeyword.value = ''
}

const switchTab = (type) => {
  tabType.value = type
  localStorage.setItem('homeTabType', type.toString())
  // 更新URL参数
  router.replace({ query: { ...route.query, tab: type.toString() } })
}

const handleTouchStart = () => {
  // 当用户触摸列表时，让搜索框失去焦点，从而收起键盘
  document.activeElement?.blur()
}

const tagsArray = (tags) => {
  return tags.split(',').slice(0, 3)
}

const toDetail = (gameId) => {
  router.push(`/detail?gameId=${gameId}`)
}

const loadGames = async () => {
  if (hasLoaded.value && games.value.length > 0) {
    return // 如果已经加载过数据且数据不为空，直接返回
  }
  
  isLoading.value = true
  try {
    const response = await fetch("/api/game/list", {
      method: "POST",
      headers: {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
      }
    });
    const data = await response.json();
    // 对数据进行排序，cate=90排最前，其他顺序不变
    games.value = data.sort((a, b) => {
      if (a.cate === 20 && b.cate !== 20) return -1;
      if (b.cate === 20 && a.cate !== 20) return 1;
      return 0;
    });
    hasLoaded.value = true
  } catch (error) {
    console.error('Error fetching games:', error);
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  loadGames()
})
</script>

<style scoped>
.content {
  padding: 16px;
  padding-bottom: 80px;
}

.game-list {
  max-width: 600px;
  margin: 0 auto;
  padding-bottom: 100px;
}

.game-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.game-item:hover {
  transform: translateY(-2px);
}

.game-icon {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 16px;
  object-fit: cover;
}

.game-info {
  flex: 1;
  min-width: 0;
}

.game-name-div {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.game-name {
  font-size: 18px;
  font-weight: bold;
  margin-right: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 12em;
  display: inline-block;
}

.tag {
  margin-right: 5px;
  background-color: #e9ecef;
  padding: 1px 4px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  display: inline-block;
  line-height: 1.2;
}

.unified-rare-tag {
  background-color: #B8860B;
  color: #FFF8DC;
  font-weight: bold;
  font-size: 12px;
  padding: 1px 4px;
  border-radius: 4px;
}

.unified-buyout-tag {
  background-color: #1976D2;
  color: #fff;
  font-weight: bold;
  font-size: 12px;
  padding: 1px 4px;
  border-radius: 4px;
}

.game-tags {
  margin-bottom: 8px;
}

.game-desc {
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.download-btn {
  padding: 8px 24px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  margin-left: 16px;
  text-decoration: none;
}

.download-btn:hover {
  background: #45a049;
}

.search-box {
  max-width: 600px;
  margin: 0 auto; /* 去掉底部间距 */
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
  height: 50px;
  display: flex;
  align-items: center;
}

.search-input {
  width: 100%;
  padding: 12px 40px 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #4CAF50;
}

.clear-btn {
  position: absolute;
  right: 12px;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
  line-height: 1;
}

.clear-btn:hover {
  color: #666;
}

.loading {
  text-align: center;
  padding: 32px;
  color: #666;
  font-size: 16px;
}

.no-result {
  text-align: center;
  padding: 32px;
  color: #999;
  font-size: 16px;
}

.tab-switch {
  display: flex;
  justify-content: center;
  margin: 0 auto; /* 去掉顶部和底部间距 */
  border-bottom: 2px solid #eee;
  background: #fff;
  max-width: 600px;
  width: 100%;
  position: sticky;
  top: 50px; /* 56px等于search-box的高度，可根据实际调整 */
  z-index: 9;
}
.tab-btn {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  color: #333;
  background: none;
  border: none;
  outline: none;
  cursor: pointer;
  position: relative;
  transition: color 0.2s;
}
.tab-btn.active {
  color: #1976D2;
}
.tab-btn.active::after {
  content: '';
  display: block;
  position: absolute;
  left: 20%;
  right: 20%;
  bottom: 0;
  height: 3px;
  background: #1976D2;
  border-radius: 2px 2px 0 0;
}

@media (max-width: 600px) {
  .content {
    padding: 8px;
  }

  .game-item {
    padding: 12px;
  }

  .game-icon {
    width: 60px;
    height: 60px;
    margin-right: 12px;
  }

  .game-name {
    font-size: 16px;
  }

  .game-desc {
    font-size: 12px;
  }
  
  .download-btn {
    padding: 6px 16px;
    font-size: 14px;
  }

  .search-input {
    padding: 8px 36px 8px 12px;
    font-size: 14px;
  }
  
  .clear-btn {
    right: 8px;
    font-size: 18px;
  }

  .tab-switch {
    max-width: 100%;
  }
}
</style> 